package com.wuwei.service;

import com.alibaba.fastjson.JSON;
import com.wuwei.utils.JDParseUtils;

import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.profile.ProfileShardResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description: ContentService <br>
 * @date: 2021/2/28 12:05 <br>
 * @author: wuwei666 <br>
 * @version: 1.0 <br>
 */
@Service
public class ContentService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 创建索引
     * @param index
     * @return
     * @throws IOException
     */
    public boolean createIndex(String index) throws IOException {
        // 索引的创建
        CreateIndexRequest indexRequest = new CreateIndexRequest(index);
        // 客户端执行请求
        CreateIndexResponse response = restHighLevelClient.indices().create(indexRequest, RequestOptions.DEFAULT);
        return response.isAcknowledged();
    }

    /**
     * 解析数据放入Es索引中
     * @param keyWord
     * @param index
     * @return
     * @throws Exception
     */
    public boolean parseContent(String keyWord,String index) throws Exception {
        List<Object> msg = JDParseUtils.getmsg(keyWord);
        BulkRequest bulkRequest = new BulkRequest();
        for (int i = 0; i < msg.size(); i++) {
            bulkRequest.add(new IndexRequest(index).source(JSON.toJSONString(msg.get(i)), XContentType.JSON));
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }

    /**
     * 关键字搜索
     * @param keyword   关键字
     * @param pageNo    页码
     * @param pageSize  页大小
     * @param index 索引
     * @return
     * @throws IOException
     */
    public List<Map<String, Object>> selectDocumentPage(String keyword, int pageNo, int pageSize, String index) throws IOException {
        if (pageNo <= 1){
            pageNo = 1;
        }
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        SearchRequest searchRequest = new SearchRequest(index);
        // 构建搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //分页
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);

        searchSourceBuilder.query(QueryBuilders.termQuery("name", keyword));
        searchSourceBuilder.timeout(new TimeValue(60,TimeUnit.SECONDS));

        //执行搜索
        searchRequest.source(searchSourceBuilder);

        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : search.getHits().getHits()) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            list.add(sourceAsMap);
        }
        return list;
    }

    /**
     *  搜索高亮
     * @param keyword   关键字
     * @param pageNo    页码
     * @param pageSize  页大小
     * @param index 索引
     * @return
     * @throws IOException
     */
    public List<Map<String, Object>> selectDocumentHighLight(String keyword, int pageNo, int pageSize, String index) throws IOException {
        if (pageNo <= 1){
            pageNo = 1;
        }
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        SearchRequest searchRequest = new SearchRequest(index);
        // 构建搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        highlightBuilder.requireFieldMatch(false);
        searchSourceBuilder.highlighter(highlightBuilder);


        //分页
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);

        searchSourceBuilder.query(QueryBuilders.termQuery("name", keyword));
        searchSourceBuilder.timeout(new TimeValue(60,TimeUnit.SECONDS));

        //执行搜索
        searchRequest.source(searchSourceBuilder);

        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        for (SearchHit hit : search.getHits().getHits()) {
            // 解析高亮的字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField name = highlightFields.get("name");

            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            // 解析高亮字段，替换掉原来的字段
            if (name != null){
                Text[] fragments = name.fragments();
                String new_name = "";
                for (Text fragment : fragments) {
                    new_name += fragment;
                }
                // 替换掉原来的内容即可
                sourceAsMap.put("name",new_name);
            }
            list.add(sourceAsMap);
        }
        return list;
    }

}
